<?php
namespace app\shop\model;

use app\BaseModel;
use app\farm\model\Coupon;
use function GuzzleHttp\Promise\is_settled;
use think\facade\Db;

class LuckDraw extends BaseModel
{
    //定义表名
    protected $name = 'lbfarm_v2_luck_draw';



    protected $append = [

        'data'

    ];
    /**
     * @param $value
     * @param $data
     * @功能说明:
     * @author chenniang
     * @DataTime: 2022-07-15 14:35
     */
    public function getDataAttr($value,$data){

        if(!empty($data['id'])){

            $config_model = new LuckConfig();

            $list = $config_model->where(['luck_id'=>$data['id'],'is_luck'=>1])->order('top,id desc')->select()->toArray();

            return $list;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        if(isset($data['data'])){

            $arr = $data['data'];

            unset($data['data']);
        }

        $res = $this->insert($data);

        $id  = $this->getLastInsID();

        if(isset($arr)){

            $this->updateSome($id,$arr,$data['uniacid']);

        }
        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-15 14:24
     * @功能说明:添加奖品信息
     */
    public function updateSome($id,$data,$uniacid){

        $config_model = new LuckConfig();

        $list = $this->changeData($data,$uniacid,$id);

        $data = array_merge($data,$list);

        $ids  = array_column($data,'id');

        $config_model->where(['luck_id'=>$id])->where('id','not in',$ids)->delete();

        if(!empty($data)){

            foreach ($data as $k=>$v){

                $v['uniacid'] = $uniacid;

                $v['luck_id'] = $id;

                if(!empty($v['id'])){

                    $config_model->dataUpdate(['id'=>$v['id']],$v);

                }else{

                    $config_model->insert($v);
                }

            }

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-26 14:50
     * @功能说明:
     */
    public function changeData($data,$uniacid,$id){

        $blance = array_sum(array_column($data,'balance'));

        $no_balance = 100-$blance;

        $no_balance = $no_balance>0?ceil($no_balance/count($data)):0;

        for ($i=1;$i<=9;$i++){

            if(!in_array($i,array_column($data,'top'))){

                $arr[] = $i;
            }

        }

        if(!empty($arr)){

            foreach ($arr as $key=> $value){

                $list[$key] = [

                    'uniacid' => $uniacid,

                    'top'     => $value,

                    'title'   => '谢谢参与',

                    'is_luck' => 0,

                    'balance' => $no_balance,

                    'luck_id' => $id,

                    'num'     => 1
                ];

            }
        }

        return !empty($list)?$list:[];
    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        if(isset($data['data'])){

            $arr = $data['data'];

            unset($data['data']);
        }

        $res = $this->where($dis)->update($data);

        if(isset($arr)){

            $this->updateSome($dis['id'],$arr,$data['uniacid']);

        }

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('top desc,id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @param $arr
     * @功能说明:抽奖算法
     * 根据概率随机中奖
     *
     * @author chenniang
     * @DataTime: 2022-07-26 14:40
     */
    public function getRand($data){

        foreach ($data as $k=>$v){

            $arr[$v['id']] = $v['balance'];
        }

        $sum = array_sum($arr);

        $res = 0;

        foreach ($arr as $key=>$value){

            $rand_num = mt_rand(1,$sum);

            if($rand_num<=$value){

                $res = $key;

                break;
            }else{

                $sum -= $value;
            }
        }

        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-29 13:54
     * @功能说明:初始化活动时间
     */
    public function initAtv(){

        $this->where('start_time','>',time())->update(['atv_status'=>1]);

        $this->where('start_time','<',time())->update(['atv_status'=>2]);

        $this->where('end_time','<',time())->update(['atv_status'=>3]);

        return true;
    }

    /**
     * @author chenniang
     * @DataTime: 2022-07-26 15:04
     * @功能说明:用户抽奖
     */
    public function luckDraw($atv_id,$user_id,$use_integral,$user_num=0){

        $config_model = new LuckConfig();
        //获取未中奖的奖项
        $list = $config_model->where(['luck_id'=>$atv_id])->where('num','>',0)->order('top,id desc')->select()->toArray();

        if(empty($list)){

            return ['code'=>500,'msg'=>'所有奖已被抽完'];
        }

        $id = $this->getRand($list);

        $data = $config_model->dataInfo(['id'=>$id]);

        $data['times'] = $user_num+1;

        if(empty($data)||($data['is_luck']==1&&$data['num']<=0)){

            $this->luckDraw($atv_id,$user_id,$use_integral);
        }

        Db::startTrans();
        //如果中奖需减数量
        if($data['is_luck']==1){

            $res = $config_model->dataUpdate(['id'=>$id,'num'=>$data['num']],['num'=>$data['num']-1]);

            if($res==0){

                Db::rollback();

                $this->luckDraw($atv_id,$user_id,$use_integral);
            }
        }
        //添加中奖记录
        $insert = [

            'uniacid'      => $data['uniacid'],

            'user_id'      => $user_id,

            'atv_id'       => $atv_id,

            'type'         => $data['type'],

            'coupon_id'    => $data['coupon_id'],

            'integral'     => $data['integral'],

            'icon'         => $data['icon'],

            'title'        => $data['title'],

            'is_luck'      => $data['is_luck'],

            'use_integral' => $use_integral,

        ];

        $record_model = new LuckRecord();

        $i_model = new IntegralLog();

        $res = $record_model->dataAdd($insert);

        if($res==0){

            Db::rollback();

            $this->luckDraw($atv_id,$user_id,$use_integral);

        }
        $record_id = $record_model->getLastInsID();

        if($data['is_luck']==1){
            //卡券
            if($data['type']==1){

                $coupon_model = new Coupon();

                $coupon = $coupon_model->dataInfo(['id'=>$data['coupon_id'],'status'=>1]);

                if(empty($coupon)){

                    Db::rollback();

                    $this->luckDraw($atv_id,$user_id,$use_integral);
                }

                $coupon_model = new \app\farm\model\CouponRecord();

                $res = $coupon_model->recordAdd($data['coupon_id'],$user_id);

                if(!empty($res['code'])){

                    Db::rollback();

                    $this->luckDraw($atv_id,$user_id,$use_integral);
                }

            }else{
                //积分
                $res = $i_model->integralUserAdd($user_id,$data['integral'],$data['uniacid'],2,14,$record_id,0,$data);

                if($res==false){

                    Db::rollback();

                    $this->luckDraw($atv_id,$user_id,$use_integral);
                }
            }
        }
        //积分
        $res = $i_model->integralUserAdd($user_id,$use_integral*-1,$data['uniacid'],2,11,$record_id,0,$data);

        if($res==false){

            Db::rollback();

            $this->luckDraw($atv_id,$user_id,$use_integral);
        }

        Db::commit();

        return $data;
    }


    /**
     * @param $input
     * @功能说明:校验时间 统一时间段只能有一个活动
     * @author chenniang
     * @DataTime: 2022-08-26 13:46
     */
    public function checkTime($input){

        if(!empty($input['start_time'])){

            $dis[] = ['uniacid','=',$input['uniacid']];

            $dis[] = ['status','>',-1];

            if(!empty($input['id'])){

                $dis[] = ['id','<>',$input['id']];
            }

            $data = $this->where($dis)->select()->toArray();

            if(!empty($data)){

                foreach ($data as $value){

                    $res = is_time_cross($input['start_time'],$input['end_time'],$value['start_time'],$value['end_time']);

                    if($res==false){

                        return ['code'=>500,'msg'=>'该时间段已经有该活动，活动名称:'.$value['title']];
                    }

                }

            }

        }

        return true;
    }














}